package com.young.mylib.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

import com.young.mylib.R;

/**
 * Created by Young on 2019/6/4.
 */

public class RoundedBackgroundSpan extends ReplacementSpan {
    private final static String TAG = "RoundedBackgroundSpan";
    private Context context;
    private int bgColor;


    public RoundedBackgroundSpan(Context context, int bgColor) {
        this.context = context;
        this.bgColor = bgColor;

    }

    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fontMetricsInt) {

        return (int) paint.measureText(text, start, end);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {

        float padding = context.getResources().getDimension(R.dimen.x3);

        float dim = context.getResources().getDimension(R.dimen.x3);

        int right = (int) x + (int) getFontWidth(paint, text, start, end);
        /**
         * x-dim可以左右PANDDING
         */

        RectF rect = new RectF(x, top + padding, right, bottom - padding);

        paint.setColor(bgColor);

        canvas.drawRoundRect(rect, dim, dim, paint);
        paint.setColor(context.getResources().getColor(android.R.color.white));

        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        int baseline = (int) (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
        paint.setTextAlign(Paint.Align.CENTER);
        String level = text.toString().substring(start, end);
        canvas.drawText(level, rect.centerX(), baseline, paint);
//        Log.i(TAG,"LEVEL: "+level);
//        String[] txts = text.toString().split(" ");
//        Log.i(TAG, text.toString());
//        if (txts.length > 1) {
//            Log.i(TAG, txts.length + " xxxx " + txts[txts.length - 1] + " start " + start+" end "+end);
//            canvas.drawText(txts[txts.length - 1], rect.centerX(), baseline, paint);
//        }


        //canvas.drawText(text, start, end, x, y, paint);
    }

    private float getFontWidth(Paint paint, CharSequence text, int start, int end) {
        return paint.measureText(text, start, end);
    }

    /**
     * @return 返回指定的文字高度
     */
    private float getFontHeight(Paint paint) {
        Paint.FontMetrics fm = paint.getFontMetrics();
        return fm.descent - fm.ascent;
    }
}